package com.gzh.teaching.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.gzh.core.dao.mapper.CommentMapper;
import com.gzh.core.dao.mapper.LikeMapper;
import com.gzh.core.dao.mapper.TopicMapper;
import com.gzh.core.dao.mapper.UserMapper;
import com.gzh.core.dao.po.CommentEntity;
import com.gzh.core.dao.po.LikeEntity;
import com.gzh.core.dao.po.TopicEntity;
import com.gzh.core.dao.po.UserEntity;
import com.gzh.core.util.NumericHelper;
import com.gzh.core.util.StringUtils;
import com.gzh.teaching.model.vo.CommentResult;
import com.gzh.teaching.service.CommentService;
import com.gzh.teaching.service.dto.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Condition;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class CommentServiceImpl implements CommentService {
  @Autowired
  private TopicMapper topicMapper;
  @Autowired
  private CommentMapper commentMapper;
  @Autowired
  private LikeMapper likeMapper;
  @Autowired
  private UserMapper userMapper;

  @Override
  public void addTopic(TopicIn in) {
    TopicEntity topicEntity = new TopicEntity();
    topicEntity.setContent(in.getContent());
    topicEntity.setCourseId(in.getCourseId());
    topicEntity.setUserId(in.getUserId());
    topicEntity.setTitle(in.getTitle());
    topicEntity.setCreateDate(NumericHelper.toInteger(StringUtils.formatDate()));
    topicEntity.setCreateTime(NumericHelper.toInteger(StringUtils.formatTime()));
    topicMapper.insertSelective(topicEntity);
  }

  @Override
  public void delTopic(TopicIn in) {
    Integer topicId = in.getTopicId();
    //删主题
    Condition topicCondition = new Condition(TopicEntity.class);
    topicCondition.createCriteria().andEqualTo("topicId",topicId);
    topicMapper.deleteByCondition(topicCondition);
    //删评论
    Condition commentCondition = new Condition(CommentEntity.class);
    commentCondition.createCriteria().andEqualTo("topicId",topicId);
    commentMapper.deleteByCondition(commentCondition);
  }

  @Override
  public void addComment(CommentIn in) {
    if (in.getSuperCommentId() != null){
      Condition commentCondition = new Condition(CommentEntity.class);
      commentCondition.createCriteria().andEqualTo("commentId",in.getSuperCommentId());
      List<CommentEntity> commentEntityList = commentMapper.selectByCondition(commentCondition);
      CommentEntity superComment = commentEntityList.get(0);
      CommentEntity commentEntity = new CommentEntity();
      commentEntity.setSuperCommentId(in.getSuperCommentId());
      if (superComment.getRootCommentId() == null){
        commentEntity.setRootCommentId(superComment.getCommentId());
      }else {
        commentEntity.setRootCommentId(superComment.getRootCommentId());
      }
      commentEntity.setContent(in.getContent());
      commentEntity.setTopicId(in.getTopicId());
      commentEntity.setUserId(in.getUserId());
      commentEntity.setCreateDate(NumericHelper.toInteger(StringUtils.formatDate()));
      commentEntity.setCreateTime(NumericHelper.toInteger(StringUtils.formatTime()));
      commentMapper.insertSelective(commentEntity);
    }else {
      CommentEntity commentEntity = new CommentEntity();
      commentEntity.setSuperCommentId(in.getSuperCommentId());
      commentEntity.setContent(in.getContent());
      commentEntity.setTopicId(in.getTopicId());
      commentEntity.setUserId(in.getUserId());
      commentEntity.setCreateDate(NumericHelper.toInteger(StringUtils.formatDate()));
      commentEntity.setCreateTime(NumericHelper.toInteger(StringUtils.formatTime()));
      commentMapper.insertSelective(commentEntity);
    }
  }

  @Override
  public void delComment(CommentIn in) {
    //删评论
    CommentEntity commentEntity = new CommentEntity();
    commentEntity.setCommentId(in.getCommentId());
    commentMapper.delete(commentEntity);
    //删子评论
    Condition commentCondition = new Condition(CommentEntity.class);
    commentCondition.createCriteria().andEqualTo("rootCommentId",in.getCommentId());
    commentMapper.deleteByCondition(commentCondition);
  }

  @Override
  public void addLike(CommentIn in) {
    Integer commentId = in.getCommentId();
    Integer topicId = in.getTopicId();
    Integer likeCount = 0;
    if (in.getCommentId()!=null){
      CommentEntity commentEntityQuery = new CommentEntity();
      commentEntityQuery.setCommentId(in.getCommentId());
      CommentEntity commentEntity = commentMapper.selectOne(commentEntityQuery);
      likeCount = commentEntity.getLikeCount();
    }
    if (in.getTopicId()!=null){
      TopicEntity topicEntityQuery = new TopicEntity();
      topicEntityQuery.setTopicId(in.getTopicId());
      TopicEntity topicEntity = topicMapper.selectOne(topicEntityQuery);
      likeCount = topicEntity.getLikeCount();
    }
    Integer count = NumericHelper.zeroNull(likeCount);
    Integer isLike = in.getIsLike();
    LikeEntity likeEntity = new LikeEntity();
    if (commentId != null){
      //修改点赞数量
      CommentEntity commentEntityUpdate = new CommentEntity();
      if (isLike == 1){
        commentEntityUpdate.setLikeCount(count + 1);
      }else {
        commentEntityUpdate.setLikeCount(count - 1);
      }
      Condition commentCondition = new Condition(CommentEntity.class);
      commentCondition.createCriteria().andEqualTo("commentId",commentId);
      commentMapper.updateByConditionSelective(commentEntityUpdate,commentCondition);
      likeEntity.setCommentId(commentId);
    }
    if (topicId != null){
      //修改点赞数量
      TopicEntity topicEntityUpdate = new TopicEntity();
      if (isLike == 1){
        topicEntityUpdate.setLikeCount(count + 1);
      }else {
        topicEntityUpdate.setLikeCount(count - 1);
      }
      Condition topicCondition = new Condition(TopicEntity.class);
      topicCondition.createCriteria().andEqualTo("topicId",topicId);
      topicMapper.updateByConditionSelective(topicEntityUpdate,topicCondition);
      likeEntity.setTopicId(topicId);
    }
    if (isLike == 1){
      //增加
      likeEntity.setUserId(in.getUserId());
      likeMapper.insertSelective(likeEntity);
    }else {
      Condition likeCondition = new Condition(LikeEntity.class);
      likeCondition.createCriteria().andEqualTo("likeId",in.getLikeId());
      likeMapper.deleteByCondition(likeCondition);
    }

  }

  @Override
  public CommentResult queryComment(CommentIn in) {
    CommentResult result = null;
    List<CommentInfo> list = new ArrayList<>();
    //
    Integer topicId = in.getTopicId();
    Integer userId = in.getUserId();
    //查看主题
    TopicEntity topicEntityQuery = new TopicEntity();
    topicEntityQuery.setTopicId(topicId);
    TopicEntity topicEntity = topicMapper.selectOne(topicEntityQuery);
    result = new CommentResult(topicEntity);
    //查找评论
    Condition commentCondition = new Condition(CommentEntity.class);
    commentCondition.createCriteria().andEqualTo("topicId",topicId);
    commentCondition.setOrderByClause("create_date desc,create_time desc");
    List<CommentEntity> commentEntityList = commentMapper.selectByCondition(commentCondition);
    result.setCommentCount("0");
    //
    List<Integer> userIdList = commentEntityList.stream().map(t -> t.getUserId()).distinct()
            .collect(Collectors.toList());
    userIdList.add(topicEntity.getUserId());
    Condition userCondition = new Condition(UserEntity.class);
    userCondition.createCriteria().andIn("userId",userIdList);
    List<UserEntity> userEntityList = userMapper.selectByCondition(userCondition);
    Map<Integer, UserEntity> userMap = userEntityList.stream().collect(Collectors.toMap(UserEntity::getUserId, Function.identity()));
    UserEntity user = userMap.get(topicEntity.getUserId());
    result.setIsTeacher(StringUtils.toString(user.getRoleId()));
    result.setUserName(user.getFullName());
    Condition condition = new Condition(LikeEntity.class);
    condition.createCriteria().andEqualTo("userId",userId)
            .andEqualTo("topicId",topicId);
    List<LikeEntity> likeEntities = likeMapper.selectByCondition(condition);
    if (!CollectionUtils.isEmpty(likeEntities)){
      result.setIsLike("1");
      result.setLikeId(StringUtils.toString(likeEntities.get(0).getLikeId()));
    }
    if (topicEntity.getUserId().equals(userId)){
      result.setIsMine("1");
    }
    if (!CollectionUtils.isEmpty(commentEntityList)){
      result.setCommentCount(StringUtils.toString(commentEntityList.size()));
      //点赞
      List<Integer> commentIdList = commentEntityList.stream().map(t -> t.getCommentId()).distinct().collect(Collectors.toList());
      Condition likeCondition = new Condition(LikeEntity.class);
      likeCondition.createCriteria().andEqualTo("userId",userId)
              .andIn("commentId",commentIdList);
      List<LikeEntity> likeEntityList = likeMapper.selectByCondition(likeCondition);
      //封装
      List<CommentEntity> entityList = commentEntityList.stream().filter(t -> t.getSuperCommentId() == null || t.getSuperCommentId() == 0)
              .collect(Collectors.toList());
      for (CommentEntity commentEntity : entityList) {
        CommentInfo info = packageComment(commentEntity, commentEntityList, likeEntityList,userMap,userId);
        list.add(info);
      }
    }
    result.setList(list);

    return result;
  }


  public CommentInfo packageComment(CommentEntity commentEntity, List<CommentEntity> commentEntityList, List<LikeEntity> likeEntityList, Map<Integer, UserEntity> userMap,Integer currentUserId){
    Integer commentId = commentEntity.getCommentId();
    CommentInfo info = new CommentInfo(commentEntity);
    List<CommentInfo> list = new ArrayList<>();
    List<LikeEntity> entities = likeEntityList.stream()
            .filter(t -> commentEntity.getCommentId().equals(t.getCommentId()) && currentUserId.equals(t.getUserId()))
            .collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(entities)){
      info.setIsLike("1");
      info.setLikeId(StringUtils.toString(entities.get(0).getLikeId()));
    }
    Integer superCommentId = commentEntity.getSuperCommentId();
    List<CommentEntity> superList = commentEntityList.stream().filter(t -> t.getCommentId().equals(superCommentId))
            .collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(superList)){
      UserEntity superUser = userMap.get(superList.get(0).getUserId());
      info.setSuperName(superUser.getFullName());
    }
    UserEntity user = userMap.get(commentEntity.getUserId());
    info.setUserName(user.getFullName());
    if (commentEntity.getUserId().equals(currentUserId)){
      info.setIsMine("1");
    }
    List<CommentEntity> entityList = commentEntityList.stream().filter(t -> commentId.equals(t.getSuperCommentId()))
            .collect(Collectors.toList());
    if (!CollectionUtils.isEmpty(entityList)){
      for (CommentEntity entity : entityList) {

        CommentInfo commentInfo = packageComment(entity, commentEntityList, likeEntityList, userMap,currentUserId);
        list.add(commentInfo);
      }
    }
    info.setList(list);
    return info;
  }

  @Override
  public TopicOut queryTopic(CommentIn in) {
    TopicOut topicOut = new TopicOut();
    List<TopicInfo> list = new ArrayList<>();
    Integer courseId = in.getCourseId();
    Integer currentUserId = in.getUserId();

    Condition topicCondition = new Condition(TopicEntity.class);
    topicCondition.createCriteria().andEqualTo("courseId",courseId);
    topicCondition.setOrderByClause("create_date desc,create_time desc");
    PageHelper.startPage(in.getPageNum(),in.getPageSize());
    Page page = PageHelper.getLocalPage();
    List<TopicEntity> topicEntities = topicMapper.selectByCondition(topicCondition);
    topicOut.setTotal(page.getTotal());
    topicOut.setPageNum(page.getPageNum());
    topicOut.setPages(page.getPages());
    topicOut.setPageSize(page.getPageSize());
    PageHelper.clearPage();
    if (!CollectionUtils.isEmpty(topicEntities)){
      List<Integer> userIdList = topicEntities.stream().map(t -> t.getUserId()).collect(Collectors.toList());
      Condition userCondition = new Condition(UserEntity.class);
      userCondition.createCriteria().andIn("userId",userIdList);
      List<UserEntity> userEntityList = userMapper.selectByCondition(userCondition);
      //
      List<Integer> topicIdList = topicEntities.stream().map(t -> t.getTopicId()).collect(Collectors.toList());
      Condition likeCondition = new Condition(LikeEntity.class);
      likeCondition.createCriteria().andEqualTo("userId",in.getUserId())
              .andIn("topicId",topicIdList);
      List<LikeEntity> likeEntityList = likeMapper.selectByCondition(likeCondition);
      Map<Integer, Integer> likeMap = likeEntityList.stream().collect(Collectors.toMap(LikeEntity::getTopicId,LikeEntity::getUserId));

      for (TopicEntity topicEntity : topicEntities) {
        TopicInfo topicInfo = new TopicInfo(topicEntity);
        Integer userId = likeMap.get(topicEntity.getTopicId());
        if (userId != null && userId != 0){
          topicInfo.setIsLike("1");
        }
        List<UserEntity> entities = userEntityList.stream().filter(t -> t.getUserId().equals(topicEntity.getUserId())).collect(Collectors.toList());
        topicInfo.setUserName(entities.get(0).getFullName());
        topicInfo.setIsTeacher(StringUtils.toString(entities.get(0).getRoleId()));
        if (topicEntity.getUserId().equals(currentUserId)){
          topicInfo.setIsMine("1");
        }
        list.add(topicInfo);
      }
    }
    topicOut.setList(list);
    return topicOut;
  }
}
